<template>
  <!-- PAGE CONTENT BEGINS -->
  <div>
    <p>
      <button v-on:click="add()" class="btn btn-white btn-warning btn-round">
        <i class="ace-icon fa fa-edit bigger-120 blue"></i>
        新增
      </button>
      &nbsp;
      <button v-on:click="list(1)" class="btn btn-white btn-warning btn-round">
        <i class="ace-icon fa fa-refresh bigger-120 blue"></i>
        刷新
      </button>
    </p>
    <paginations ref="paginations" v-bind:list="list"></paginations>
    <table id="simple-table" class="table  table-bordered table-hover">
      <thead>
      <tr>
        <th> ID </th>
        <th> 角色 </th>
        <th> 描述 </th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="role in roles" :key="role.num">
          <td> {{role.id}} </td>
          <td> {{role.name}} </td>
          <td> {{role.desc}} </td>
        <td>
          <div class="hidden-sm hidden-xs btn-group">
            <button v-on:click="editResource(role)" class="btn btn-xs btn-info">
              <i class="ace-icon fa fa-list bigger-120"></i>资源
            </button>

            <button v-on:click="editUser(role)" class="btn btn-xs btn-info">
              <i class="ace-icon fa fa-user bigger-120"></i>用户
            </button>

            <button v-on:click="edit(role)" class="btn btn-xs btn-info">
              <i class="ace-icon fa fa-pencil bigger-120"></i>编辑
            </button>

            <button v-on:click="del(role.id)" class="btn btn-xs btn-danger">
              <i class="ace-icon fa fa-trash-o bigger-120"></i>删除
            </button>
          </div>

          <div class="hidden-md hidden-lg">
            <div class="inline pos-rel">
              <button class="btn btn-minier btn-primary dropdown-toggle" data-toggle="dropdown" data-position="auto">
                <i class="ace-icon fa fa-cog icon-only bigger-110"></i>
              </button>

              <ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close">
                <li>
                  <a href="#" class="tooltip-info" data-rel="tooltip" title="View">
                    <span class="blue">
                      <i class="ace-icon fa fa-search-plus bigger-120"></i>
                    </span>
                  </a>
                </li>

                <li>
                  <a href="#" class="tooltip-success" data-rel="tooltip" title="Edit">
                    <span class="green">
                      <i class="ace-icon fa fa-pencil-square-o bigger-120"></i>
                    </span>
                  </a>
                </li>

                <li>
                  <a href="#" class="tooltip-error" data-rel="tooltip" title="Delete">
                    <span class="red">
                      <i class="ace-icon fa fa-trash-o bigger-120"></i>
                    </span>
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </td>
      </tr>
      </tbody>
    </table>
    <!--编辑模态框-->
    <div class="modal fade" id="myFormModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">表单</h4>
          </div>
          <div class="modal-body">
            <!--表格-->
            <form class="form-horizontal">
              <div class="form-group">
                <label class="col-sm-2 control-label">角色</label>
                <div class="col-sm-10">
                  <input v-model="role.name" class="form-control" placeholder="输入角色"/>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">描述</label>
                <div class="col-sm-10">
                  <input v-model="role.desc" class="form-control" placeholder="输入描述"/>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" v-on:click="save()">保存</button>
          </div>
        </div><!-- /.modal-content-->
      </div><!-- /.modal-dialog-->
    </div><!-- /.modal-->
    <!--角色权限模态框-->
    <div class="modal fade" id="ResourceModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="ResourceModalLabel">角色资源关联配置</h4>
          </div>
          <div class="modal-body">
            <ul id="tree" class="ztree"></ul>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
              <i class="ace-icon fa fa-times"></i>
              关闭
            </button>
            <button type="button" class="btn btn-primary" v-on:click="saveResource()">
              <i class="ace-icon fa fa-plus blue"></i>
              保存
            </button>
          </div>
        </div><!-- /.modal-content-->
      </div><!-- /.modal-dialog-->
    </div><!-- /.modal-->
    <!--角色用户模态框-->
    <div class="modal fade" id="UserModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="UserModalLabel">角色用户关联配置</h4>
          </div>
          <div class="modal-body">
            <!--角色用户div-->
            <div class="row">
              <div class="col-md-6">
                <small-paginations ref="paginations" v-bind:list="listUser"></small-paginations>
                <table id="user-table" class="table table-hover">
                  <tbody>
                  <tr v-for="user in users" :key="user.num">
                    <td>{{user.username}}</td>
                    <td class="text-right">
                      <a v-on:click="addUser(user)" href="javascript:;" class="">
                        <i class="ace-icon fa fa-arrow-circle-right blue"></i>
                      </a>
                    </td>
                  </tr>
                  </tbody>
                </table>
                <hr>
              </div>
              <div class="col-md-6">
                <table id="role-user-table" class="table table-hover">
                  <tbody>
                  <tr v-for="user in roleUsers" :key="user.num">
                    <td>
                      {{user.username}}
                      <span class="pull-right label label-primary round info-label">
                        {{role.name}}
                      </span>
                    </td>

                    <td class="text-right">
                      <a v-on:click="deleteUser(user)" href="javascript:;" class="">
                        <i class="ace-icon fa fa-trash red"></i>
                      </a>
                    </td>
                  </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
              <i class="ace-icon fa fa-times"></i>
              关闭
            </button>
            <button type="button" class="btn btn-primary" v-on:click="saveRoleUser()">
              <i class="ace-icon fa fa-plus blue"></i>
              保存
            </button>
          </div>
        </div><!-- /.modal-content-->
      </div><!-- /.modal-dialog-->
    </div><!-- /.modal-->
  </div>
</template>
<script>
import Paginations from "../../components/paginations";
import SmallPaginations from "../../components/small-paginations";
export default {
  name: 'system-role',
  components: {Paginations,SmallPaginations},
  data: function (){
    return{
      //映射表单数据
      role: {},
      roles: [],
      resources:[],
      zTree:{},
      users:[],
      roleUsers:[],
    }
  },
  mounted:function (){
    let _this = this;
    _this.list(1);
  },
  methods:{

    add() {
      let _this = this;
      _this.role = {};
      $("#myFormModal").modal("show");
    },

    edit(role) {
      let _this = this;
      _this.role = $.extend({},role);
      $("#myFormModal").modal("show");
    },
    /**查询*/
    list(page){
      let _this = this;
      Loading.show();
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/role/list',{
        page:page,
        size:_this.$refs.paginations.size,
      }).then((response)=>{
        Loading.hide();
        console.log("查询角色列表结果：",response);
        let resp = response.data;
        _this.roles = resp.content.list;
        _this.$refs.paginations.render(page,resp.content.total);
      })
    },
    /**保存*/
    save(){
      let _this = this;
      /**保存校验*/
      if(1 != 1
      || !Validator.require(_this.role.name,"角色")
      || !Validator.length(_this.role.name,"角色",1,50)
      || !Validator.require(_this.role.desc,"描述")
      || !Validator.length(_this.role.desc,"描述",1,100)
      ){
        return;
      }
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/role/save',_this.role)
      .then((response)=>{
        console.log("保存角色列表结果：",response);
        let resp = response.data;
        if(resp.success){
          $("#myFormModal").modal("hide");
          _this.list(1);
          toast.success("保存成功！");
        }else{
          toast.warning(resp.message);
        }


      })
    },
    /**删除*/
    del(id){
      let _this = this;
      //弹出框
      Confirm.show("删除角色后不可恢复，您是否检查删除!",function (){
        _this.$ajax.delete(process.env.VUE_APP_SERVER + '/system/admin/role/delete/'+ id )
            .then((response)=>{
              console.log("删除角色列表结果：",response);
              let resp = response.data;
              if(resp.success){
                _this.list(1);
                toast.success("删除成功！");
              }
            });
      })
    },
    /**打开资源编辑框*/
    editResource(role){
      let _this = this;
      _this.role = $.extend({},role);
      _this.loadResource();
      $("#ResourceModal").modal("show");
    },
    /**加载资源树*/
    loadResource(){
      let _this = this;
      Loading.show();
      _this.$ajax.get(process.env.VUE_APP_SERVER + '/system/admin/resource/load-tree').then((response)=>{
        Loading.hide();
        let resp = response.data;
        _this.resources = resp.content;
        //初始化树
        _this.initTree();
        _this.listRoleResource();
      })
    },
    /**初始化资源树*/
    initTree(){
      let _this = this;
      let setting = {
        check:{
          enable:true
        },
        data:{
          simpleData:{
            idKey:"id",
            pIdKey:"parent",
            rootPId:"",
            enable: true
          }
        }
      };
      _this.zTree = $.fn.zTree.init($("#tree"),setting,_this.resources);
      _this.zTree.expandAll(true);

    },
    /**资源模态框保存*/
    saveResource(){
      let _this = this;
      let resources = _this.zTree.getCheckedNodes();
      console.log("勾选的资源：",resources);

      //保存时，只需要保存资源id，所以使用id数组进行参数传递
      let resourceIds =[];
      for(let i=0;i<resources.length;i++){
        resourceIds.push(resources[i].id);
      }

      _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/role/save-resource',{
        id:_this.role.id,
        resourceIds:resourceIds
      }).then((response)=>{
        let resp = response.data;
        if(resp.success){
          toast.success("保存成功!")
        }else{
          toast.warning(resp.message);
        }
      });

    },
    /**加载资源角色*/
    listRoleResource(){
      let _this = this;
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/role/list-resource/' + _this.role.id).then((response)=>{
        let resp = response.data;
        let resources = resp.content;

        _this.zTree.checkAllNodes(false);

        for(let i = 0;i < resources.length;i++){
          let node = _this.zTree.getNodeByParam("id" , resources[i]);
          _this.zTree.checkNode(node,true);
        }
      });
    },
    /**打开用户编辑框*/
    editUser(role){
      let _this = this;
      _this.role = $.extend({},role);
      _this.listUser(1);
      _this.listRoleUser();
      $("#UserModal").modal("show");
    },
    /**查询所有用户*/
    listUser(page){
      let _this = this;
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/userInfo/list',{
        page:page,
        size:_this.$refs.paginations.size,
      }).then((response)=>{
        let resp = response.data;
        if(resp.success){
          _this.users = resp.content.list;
          _this.$refs.paginations.render(page,resp.content.total);
          console.log(_this.users);
        }else {
          toast.warning(resp.message);
        }
      });
    },
    /**添加用户到数组*/
    addUser(user){
      let _this = this;
      let users = _this.roleUsers;
      for(let i =0;i<users.length;i++){
        if(user === users[i]){
          toast.warning("该用户已拥有角色权限");
          return;
        }
      }
      _this.roleUsers.push(user);
    },
    /**删除用户到数组*/
    deleteUser(user){
      let _this = this;
      Tool.removeObj(_this.roleUsers,user);
    },
    /**保存用户-角色关联数据*/
    saveRoleUser(){
      let _this = this;
      let users = _this.roleUsers;
      let userIds = [];
      for(let i = 0;i < users.length;i++){
        userIds.push(users[i].id);
      }
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/role/save-user',{
        id:_this.role.id,
        userIds:userIds
      }).then((response)=>{
        let resp = response.data;
        if(resp.success){
          toast.success("保存成功!");
        }else{
          toast.warning(resp.message);
        }
      });
    },
    /**加载用户-角色*/
    listRoleUser(){
      let _this = this;
      this.roleUsers = [];
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/role/list-user/' + _this.role.id).then((response)=>{
        let resp = response.data;
        let userIds= resp.content;
        for(let i = 0;i < userIds.length;i++) {
          for(let j = 0;j < _this.users.length;j++){
            if(userIds[i]===_this.users[j].id){
              _this.roleUsers.push(_this.users[j]);
            }
          }
        }
      });
    },
  }
}
</script>
